<?php
/**
 * 管理员管理入口
 *
 * @author can.weng <wengcanvip@gmail.com>
 * @copyright ©2012-2012 http//youngme.me
 * @license http//youngme.me
 * @version v1.00
 */
class admin extends common
{
	/**
	 *config for the admin contorl panel
	 * 
	 */
	private $configuration=array(
			'site'  =>'网站后台管理系统',
			'verify'=>true,//是否开启验证码
			'repass'=>false,//是否开启密码找回
			'backup'=>true,
			'mail'=>false,
			'page'=>15,
			'copyright'=>'网站版权',
			);
	/**
	 *
	 * 
	 */		
	function __construct(){
		parent::__construct();
		define("CURRENT_PATH",dirname(__FILE__));		
		require(CURRENT_PATH.'/lib/lib_common.php');
	    spAddViewFunction('insert_scripts','smarty_insert_scripts');
	    $a=($a=$this->spArgs('a'))!=""?$a:'index';
		$mod=($mod=$this->spArgs('mod'))!=""?$mod:'index';
		if(!in_array($a,array('login','logout','loginAction'))){//these acton do not need to check the users` login status
			$this->chkLog();
			$topArray=array('index','tech','special','live','feedback','user','help');
			$authTemp=unserialize($_SESSION['authority']);
//**==============================      权限控制      =============================================**//




//**=============================================================================================**//
			require(CURRENT_PATH.'/include/'.$a.'.php');	
		}	
		unset($a);
	}
	/**
	 * use to check log in status after already login
	 * 
	 */	
	private function chkLog(){
		if(!isset($_SESSION['admin'])|| true != $_SESSION['admin'] ){
			$this->jump(spUrl('admin', 'login')); 
			die;
		}else{
			$tempchk=spClass(manage)->find($conditons=array('id'=>$_SESSION['id']));
			if($_SESSION['sessid']!=$tempchk['sessid']){
				session_destroy();
				$this->error("您的账户已经在别处登录！",spUrl("admin","index"));
			}
			
		}
		
	}
	
	private function loglock(){
		if(isset($_SESSION['locktime']) && time()-$_SESSION['locktime']<=15*60){
			$this->locktime=$_SESSION['locktime']+15*60-time();
			$this->display('admin/msg/lock.html');
			exit;
		}		
	}		
	
	/**
	 * test if the password is correct
	 * 
	 */		
	private function chkpass($pass,$sigPassword){
		import(APP_PATH.'/controller/lib/class-phpass.php');
		$hasher = new PasswordHash(8, TRUE);
		$Login=$hasher->CheckPassword($pass,$sigPassword);
		return $Login;
	}
	/**
	 * generact a new password to insert the datebase
	 * 
	 */		
	private function passgen($pass){
		import(APP_PATH.'/controller/lib/class-phpass.php');
		$passwordValue = $pass;  
		$hasher = new PasswordHash(8, TRUE);  
		return $hasher->HashPassword($passwordValue);
	}

	function  loginAction(){
		//var_dump($this->spArgs());
		//var_dump($_SESSION);
		$this->loglock();
		$sessid=$_COOKIE['PHPSESSID'];		
if($this->configuration['verify']){//检查验证码配置；
			$verifyCondition=md5(strtoupper($this->spArgs(captcha)))==$_SESSION['verify'];//将用户输入验证码转换为大写
		}else{
			$verifyCondition=1;
		}
		if($verifyCondition){
			if($this->spArgs('auth')!='WISE'){
				$this->error("网站管理码错误，请检查！",spUrl("admin","index"));	
			}			
			$LogIn=spClass(manage);
			$P=null;
			$P=$LogIn->find($conditions=array('username'=>$this->spArgs(username)),'',$fields=null);
			$sigPassword=$P[password];
			if($this->chkpass($this->spArgs(password),$sigPassword)){
					$Login=$P;
					unset($P);
					unset($_SESSION['verify']);
					$_SESSION['adminUserName'] = $Login['username'];
					$_SESSION['admin']         = true;
					$_SESSION['adminType']     = $Login['system'];//1 root 0 一般
					$_SESSION['authority']     = $Login['auth'];	//管理员权限序列化后的数组
					$_SESSION['id']            = $Login['id'];	//用户ID
					$_SESSION['sessid']        = $sessid;//用户sessionID
					//$this->success('恭喜，登录成功！', spUrl('admin', 'index'));
					$LogIn->updatefield($conditions=array('id'=>$Login['id']),'sessid',$sessid);//更新数据库中所存储的sessionid
					unset($_SESSION['ecount'],$_SESSION['logtime'],$_SESSION['locktime']);
					$this->guide('恭喜登录成功，正在为您跳转至系统管理页',spUrl('admin', 'index')); 
				}else{
					$_SESSION['ecount']=isset($_SESSION['ecount'])?$_SESSION['ecount']:1;
					$lastlogtime=isset($_SESSION['logtime'])?$_SESSION['logtime'] : time();
					if(time()-$lastlogtime <=60 *5){//两次登录间隔小于5min
						$_SESSION['ecount']++;
					}else{
						$_SESSION['ecount']=1;
					}
					if($_SESSION['ecount']==5 ){//出错5次锁定15min
						unset($_SESSION['ecount'],$_SESSION['logtime']);
						$_SESSION['locktime']=time();
						$this->loglock();					
					}else{	
						$_SESSION['logtime']=time();			
						$this->error("登陆失败，请仔细检查您的用户名和密码！",spUrl("admin","index"));	
					}
				}
			}else{
				//$this->error("验证码输入有误，请勿禁用浏览器javascript！",spUrl("admin","index"));
				$this->jump(spUrl("admin","index"));			
			}		

		
	}
	/**
	 * 
	 * 
	 */	
	function login(){
		unset($_SESSION['locktime']);
		$this->loglock();
		$this->config=$this->configuration;
		$this->display('admin/login.html');
	}
	/**
	 * 
	 * 
	 */	
	function logout(){
		//session_unset();//释放内存session变量,不删除session_id  
		session_destroy();//删除session文件与session_id 
		$this->jump(spUrl('admin', 'index'));		
	}
	function index()   {}
	function tech()    {}
	function special() {}
	function live()    {}
	function feedback(){}
	function user()    {}
	function help()    {}
	/**
	*
	*/
	private function guide($msg,$url){
		$this->msg=$msg;
		$this->url=$url;
		$this->display('management/guide.html');		
	}
	private function sqlGen1($mapArr,$tempArr,$field){
		$sql="";
		foreach($mapArr as $k => $v){
			$sql.='when '.$v.' then \''.mysql_real_escape_string($tempArr[$k]).'\'';
		}
		return $sql;
	}
	private function DataToSave($saveMapArr,$arraytemp,$newrow=array()){
		foreach($saveMapArr as $id=>$v){
			$tempArr=array($v=>$arraytemp[$id]);
			$newrow=array_merge($newrow,$tempArr);
		}
			unset($saveMapArr,$arraytemp,$tempArr);
		return $newrow;	
	}
/**
 *@param $model ,$id,$status ,$flag 
 *
 */	
	private function showstatus($modle,$id,$status,$flag=true){
		$temp=spClass($modle);
		$tempres=$temp->find(array('id'=>$id),null,'system,show_status');
		if(!$tempres){
			$this->error("记录不存在！");
		}else if($tempres['show_status']==$status){
			$this->error("显示状态未更改！");
		}else if($flag){
			if($res['system']==1){
				$this->error("此记录显示状态无需更改！");	
			}
		}else{
			$temp->updateField($conditions=array('id'=>$id), $field='show_status',$status);
			$this->success("恭喜！显示状态修改成功！");
		}
	
	}
/**
 *@param $model ,$id,$status ,$flag 
 *
 */		
	private function stick($modle,$id,$order="100000",$flag=true){
		$temp=spClass($modle);
		$tempres=$temp->find(array('id'=>$id),null,'system');
		if(!$tempres){
			$this->error("记录不存在！");
		}else if($flag){
			if($res['system']==1){
				$this->error("此记录显示顺序无需更改！");	
			}
		}else{
			$temp->updateField($conditions=array('id'=>$id), $field='show_status',$order);
			$this->success("恭喜！显示顺序修改成功！");
		}	
	}	
}